package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.EmployeeService;
import cn.wolfcode.crm.service.PermissionService;
import cn.wolfcode.crm.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;


public class EmployeeRealm extends AuthorizingRealm {

    private EmployeeService employeeService;
    private RoleService roleService;
    private PermissionService permissionService;

    public  void setEmployeeService(EmployeeService employeeService){
        this.employeeService=employeeService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken =(UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
       Employee employee = employeeService.queryByUsername(username);
       if (employee!=null){
           return new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getName()),this.getName());
       }

        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前访问用户
        Employee employee=(Employee)principalCollection.getPrimaryPrincipal();
        //判断当前用户是否是超级管理员,授予admin的角色和所有权限
        if(employee.isAdmin()){
            info.addRole("admin");
            info.addStringPermission("*:*");
            return info;
        }
        // 根据访问用户的 id 查询到其拥有的所有角色的编码
        List<String> roleSns = roleService.queryRoleSnsByEmployeeId(employee.getId());
        // 根据登录用户的 id 查询到其拥有的所有权限表达式
        List<String> expressions = permissionService.querByEmployeeId(employee.getId());
        // 将用户拥有的角色和权限添加到授权信息对象中，供 Shiro 权限校验时使用
        info.addRoles(roleSns);
        info.addStringPermissions(expressions);
        return info;
    }

    }






